//
//  QKEasyAlbumController.m
//  EasyIOS
//
//  Created by ChiCo on 2017/5/2.
//  Copyright © 2017年 EasyIOS. All rights reserved.
//

#import "QKEasyAlbumController.h"
#import "QKEasyAlbumCell.h"
#import <Photos/Photos.h>
#import "QKEasyAlbumTopBar.h"
#import "QKEasyAlbumBottomBar.h"

@interface QKEasyAlbumController () <UICollectionViewDelegate,UICollectionViewDataSource,PHPhotoLibraryChangeObserver>

/**
 * 选择后的照片源数据
 */
@property (nonatomic,strong)NSMutableArray <PHAsset *>*chosedAssets;



/**
 * chosed: YES 选择照片完成 NO 取消选择照片
 * assets: 选择的照片
 */
@property (nonatomic,copy)void (^finish)(BOOL chosed,NSMutableArray <UIImage *>*assets);

/**
 * 最多可选
 */
@property (nonatomic,assign)NSUInteger maxNumber;

/**
 * 最低可选
 */
@property (nonatomic,assign)NSUInteger minNumber;

/**
 * 可供展示的照片
 */
@property (nonatomic,strong)PHFetchResult *fetchResult;

/**
 * 选择照片的张数
 */
@property (nonatomic,assign)NSUInteger choosedNumber;

/**
 * 已选照片的位置
 */
@property (nonatomic,strong)NSMutableArray <NSIndexPath *>*chosedIndexPath;


@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)QKEasyAlbumBottomBar *bottomBar;

@end

@implementation QKEasyAlbumController

+ (QKEasyAlbumController *)showAlblumWithController:(UIViewController *)controller
                                          maxNumber:(NSUInteger)maxNumber
                                         minNumuber:(NSUInteger)minNumber
                                             finish:(void (^)(BOOL, NSMutableArray<UIImage *> *))finish
{
    QKEasyAlbumController *album = [[QKEasyAlbumController alloc] init];
    album.maxNumber = maxNumber;
    album.minNumber = minNumber;
    album.finish = finish;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:album];
    nav.navigationBarHidden = YES;
    [controller presentViewController:nav
                             animated:YES
                           completion:NULL];
    return album;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setUpSubViews];
    [self loadData];
    [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
}

- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    //改变数据了,重新加载一下
    [self loadData];
    
}

- (void)loadData
{
    self.chosedAssets = [NSMutableArray array];
    self.chosedIndexPath = [NSMutableArray array];
    
    //没有权限要申请权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        NSString *alerString = [NSString stringWithFormat:@"允许%@访问你的手机相册", appName];
        UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"使用相册" message:alerString preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [aletController addAction:cancelAction];
        [aletController addAction:setAction];
        [self presentViewController:aletController animated:YES completion:NULL];
        
    }
    
    @weakify(self);
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus authorizationStatus) {
        @strongify(self);
        if (authorizationStatus == PHAuthorizationStatusAuthorized) {
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
            PHFetchResult *request = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
            self.fetchResult = request;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                NSUInteger count = [self.fetchResult count];
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:(NSInteger)count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
            });
        }
    }];
    
    
}

- (void)setUpSubViews
{
    [self setupCollectionView];
    CGFloat barHeight = 44;
    if(KScreenHeight >= 812) barHeight = 78;
    QKEasyAlbumTopBar *topBar = [[QKEasyAlbumTopBar alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, barHeight)];
    [topBar.backButton addTarget:self
                          action:@selector(cacelAction)
                forControlEvents:UIControlEventTouchUpInside];
    [topBar.cancelButton addTarget:self
                            action:@selector(cacelAction)
                  forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBar];
    
    self.bottomBar = [[QKEasyAlbumBottomBar alloc] initWithFrame:CGRectMake(0, KScreenHeight-90,
                                                                           KScreenWidth, 90) chosedAssets:self.chosedAssets
                                                       maxNumber:self.maxNumber];
    @weakify(self);
    [self.bottomBar setDeletAsset:^(PHAsset *asset){
        @strongify(self);
        NSUInteger index = [self.fetchResult indexOfObject:asset];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(NSInteger)index inSection:0];
        [self.chosedIndexPath removeObject:indexPath];
        NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
        if ([visibleItems containsObject:indexPath]) {
            QKEasyAlbumCell *cell = (QKEasyAlbumCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            cell.chosed = NO;
        }
    }];
    [self.bottomBar.nextButton addTarget:self
                                  action:@selector(sureAction)
                        forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.bottomBar];
    
}

- (void)sureAction
{
    @weakify(self);
    if ([self.chosedIndexPath count] < self.minNumber) {
        NSString *errorString = [NSString stringWithFormat:@"最少选%d张",(int)self.minNumber];
        NSLog(@"%@",errorString);
        return;
    }
    if (self.finish) {
       
        NSMutableArray *array = [NSMutableArray array];
        dispatch_group_t group  = dispatch_group_create();
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        for (NSUInteger index = 0; index < self.bottomBar.chosedAssets.count; index++) {
            
            dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                @strongify(self);
                PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
                option.synchronous = YES;
                option.networkAccessAllowed = YES;
                option.resizeMode = PHImageRequestOptionsResizeModeFast;
                option.deliveryMode = PHImageRequestOptionsResizeModeExact;
                PHAsset *assert = [self.bottomBar.chosedAssets objectAtIndex:index];
                [[PHImageManager defaultManager] requestImageForAsset:assert targetSize:CGSizeMake(assert.pixelWidth, assert.pixelHeight) contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    if (!result) {
                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                        NSLog(@"选取图片失败");
                        return ;
                    }
                    [array addObject:result];
                }];
            });
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            self.finish(YES, [array copy]);
            [self dismissViewControllerAnimated:YES completion:NULL];
        });
       
    }
  
}

- (void)cacelAction
{
    if (self.finish) {
        self.finish(NO, nil);
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)setupCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 2.5;
    layout.minimumInteritemSpacing = 2.5;
    CGFloat width = (KScreenWidth-12.5)/4;
    layout.itemSize = CGSizeMake(width, width);
    self.title = @"全部照片";
    CGFloat topHeight = 44;
    if (KScreenHeight >= 812) topHeight = 78;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(2.5, topHeight, KScreenWidth-5, KScreenHeight-topHeight-90) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    [self.collectionView registerClass:[QKEasyAlbumCell class] forCellWithReuseIdentifier:@"EasyAlbumCell"];
    [self.collectionView setBackgroundColor:[UIColor blackColor]];
    [self.view setBackgroundColor:[UIColor blackColor]];
    
    //滚动视图不需要全屏切换
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    // Fallback on earlier versions
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (NSInteger)[self.fetchResult count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QKEasyAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EasyAlbumCell" forIndexPath:indexPath];
    cell.asset = [self.fetchResult objectAtIndex:(NSUInteger)indexPath.row];
    cell.chosed = [self.chosedIndexPath containsObject:indexPath];

    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    QKEasyAlbumCell *cell = (QKEasyAlbumCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (cell.chosed) {
        cell.chosed = NO;
        [self.chosedIndexPath removeObject:indexPath];
        [self.bottomBar deleteAsset:cell.asset];
        
    } else {
        if([self.chosedIndexPath count] >= self.maxNumber)
        {
            NSString *errorString = [NSString stringWithFormat:@"最多选%d张",(int)self.maxNumber];
            NSLog(@"%@",errorString);
            return;
        }
        cell.chosed = YES;
        [self.chosedIndexPath addObject:indexPath];
        [self.bottomBar addAsset:cell.asset];
    }
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}


@end
